<script setup>
import { updateUserPwdApi } from "@/api/user";
import { ElMessage } from "element-plus";
import { ref } from "vue";

const pwdForm = ref({
  old_pwd: "",
  new_pwd: "",
  re_pwd: "",
});

const pwdFormRules = {
  old_pwd: [
    { required: true, message: "请输入旧密码", trigger: "blur" },
    {
      pattern: /^\S{6,15}$/,
      message: "密码长度必须是6-15位的非空字符串",
      trigger: "blur",
    },
  ],
  new_pwd: [
    { required: true, message: "请输入新密码", trigger: "blur" },
    {
      pattern: /^\S{6,15}$/,
      message: "密码长度必须是6-15位的非空字符串",
      trigger: "blur",
    },
    {
      validator(rule, value, callback) {
        if (value !== pwdForm.value.old_pwd) {
          callback();
        } else {
          callback(new Error("新密码与旧密码不能相同"));
        }
      },
      trigger: "blur",
    },
  ],
  re_pwd: [
    { required: true, message: "请输入确认密码", trigger: "blur" },
    {
      validator(rule, value, callback) {
        if (value !== pwdForm.value.new_pwd) {
          callback(new Error("新密码与确认密码不一致"));
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
  ],
};

const pwdFormRef = ref(null);

// 重置
const reset = () => {
  pwdFormRef.value.resetFields();
};

// 修改密码
const changePwd = () => {
  pwdFormRef.value.validate(async (valid) => {
    if (!valid) return;

    // 1.ajax
    const { data: res } = await updateUserPwdApi(pwdForm.value);
    // 失败
    if (res.code !== 0) return ElMessage.error(res.message);
    // 成功
    ElMessage.success(res.message);

    pwdFormRef.value.resetFields();
  });
};
</script>

<template>
  <el-card class="box-card">
    <template #header>
      <div class="card-header">
        <h3>重置密码</h3>
      </div>
    </template>
    <!-- 表单 -->
    <el-form
      :model="pwdForm"
      :rules="pwdFormRules"
      ref="pwdFormRef"
      label-width="100px"
    >
      <el-form-item label="原密码" prop="old_pwd">
        <el-input v-model="pwdForm.old_pwd" type="password"></el-input>
      </el-form-item>
      <el-form-item label="新密码" prop="new_pwd">
        <el-input v-model="pwdForm.new_pwd" type="password"></el-input>
      </el-form-item>
      <el-form-item label="确认新密码" prop="re_pwd">
        <el-input v-model="pwdForm.re_pwd" type="password"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="changePwd">修改密码</el-button>
        <el-button @click="reset">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<style scoped></style>
